package com.memory.admin.sell.controller;

import com.memory.common.exception.ResultException;
import com.memory.common.utils.ResultVoUtil;
import com.memory.common.vo.ResultVo;
import com.memory.modules.business.domain.sell.InvoiceRecord;
import com.memory.modules.business.service.sell.InvoiceRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * @PackageName: com.memory.admin.sell.controller
 * @ClassName: InvoiceRecordController
 * @Description:
 * @author: zhuguangxun
 * @date 2021/3/13
 */
@Controller
@RequestMapping("/business/invoice/record")
@RequiredArgsConstructor
public class InvoiceRecordController {

    private final static String PATH = "/business/invoicerecord/";

    private final InvoiceRecordService invoiceRecordService;

    @GetMapping("list")
    public String list(InvoiceRecord invoiceRecord, Model model) {
        ExampleMatcher matcher = ExampleMatcher.matching();
        Example<InvoiceRecord> example = Example.of(invoiceRecord, matcher);
        final Page<InvoiceRecord> page = invoiceRecordService.findPage(example);
        model.addAttribute("list", page.getContent());
        model.addAttribute("page", page);
        return PATH + "list";
    }

    @GetMapping("add")
    public String add(Model model) {
        return PATH + "add";
    }

    @GetMapping("edit/{id}")
    public String edit(@PathVariable("id") Long id, Model model) {
        final Optional<InvoiceRecord> byId = invoiceRecordService.findById(id);
        model.addAttribute("invoiceRecord", byId.orElseThrow(() -> new ResultException(500, "未获取发票记录")));
        return PATH + "add";
    }

    @PostMapping("save")
    public @ResponseBody
    ResultVo save(InvoiceRecord invoiceRecord, Model model) {
        if (invoiceRecord.getId() == null) {
            final InvoiceRecord invoiceRecord1 = invoiceRecordService.create(invoiceRecord);
        } else {
            final InvoiceRecord modify = invoiceRecordService.modify(invoiceRecord.getId(), invoiceRecord);
        }
        return ResultVoUtil.SAVE_SUCCESS;
    }

    @GetMapping("remove/{id}")
    public ResultVo remove(@PathVariable("id") Long id) {
        final InvoiceRecord remove = invoiceRecordService.remove(id);
        return ResultVoUtil.success();
    }
}
